from rest_framework import viewsets
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from .models import Category, Product
from .serializers import CategorySerializer, ProductDetailSerializer, ProductListSerializer
from ..common.paginator import MyPageNumberPagination


class CategoryViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = Category.objects.all()
    serializer_class = CategorySerializer
    permission_classes = [AllowAny]

    def list(self, request, *args, **kwargs):
        queryset = Category.objects.filter(parent=None)  # 获取所有顶级类目
        serializer = CategorySerializer(queryset, many=True)
        return Response(serializer.data)


class ProductViewSet(viewsets.ReadOnlyModelViewSet):
    """
    产品视图集，提供产品的CRUD操作。
    """
    queryset = Product.objects.all()
    permission_classes = [AllowAny]
    pagination_class = MyPageNumberPagination

    def get_serializer_class(self):
        """
        根据请求的动作返回不同的序列化器。
        """
        if self.action == 'list':
            return ProductListSerializer
        return ProductDetailSerializer
